package study_thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-12-12 19:50
 **/
public class Test_ReentrantLock {


    public static void main(String[] args) {
        interrupt();
    }

    /**
     * 简单看一下写法
     */
    public static void reentrantLock() {
        Lock lock = new ReentrantLock(); // implements Lock
        try {
            lock.lock(); //等同于 synchronized(this)
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); //  务必在最后手动解锁，否则将造成死锁
        }
    }

    /**
     * ReentrantLock 支持 "尝试加锁" 的操作：
     */
    public static void tryLock() {
        Lock lock = new ReentrantLock();
        boolean locked = false;
        try {
            //尝试加锁，如果加不上则退出加锁操作，程序继续执行
            locked = lock.tryLock(2, TimeUnit.SECONDS);
            System.out.println(locked);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (locked) lock.unlock();
        }
    }

    /**
     * ReentrantLock 支持被 "打断"
     */
    public static void interrupt() {
        Lock lock2 = new ReentrantLock();
        Thread t2 = new Thread(() -> {
            try {
                lock2.lockInterruptibly(); //可以对interrupt()方法做出响应
                System.out.println("t2 start");
                TimeUnit.SECONDS.sleep(5);
                System.out.println("t2 end");
            } catch (InterruptedException e) {
                System.out.println("被打断");
            } finally {
                lock2.unlock();
            }
        });
        t2.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.interrupt(); //打断线程2的等待

    }

}
